#pragma once
#include "requestor.hpp"
#include <unordered_set>

namespace RPC
{
    namespace client
    {
        class Provider
        {
        public:
            using ptr = std::shared_ptr<Provider>;
            Provider(const Requestor::ptr &requestor)
                : _requestor(requestor)
            {
            }

            bool registryMethod(const BaseConnection::ptr &conn, const std::string &method, const Address &host)
            {
                auto msg_req = MessageFactory::create<ServiceRequest>();
                UUID u;
                msg_req->setId(u.uuid());
                msg_req->setMType(MType::REQ_SERVICE);
                msg_req->setMethod(method);
                msg_req->setHost(host);
                msg_req->setOptype(ServiceOpType::SERVICE_REGISTRY);
                BaseMessage::ptr msg_rsp;
                bool ret = _requestor->send(conn, msg_req, msg_rsp);
                if (ret == false)
                {
                    ELOG("%s 服务注册失败! ", method.c_str());
                    return false;
                }

                auto servise_rsp = std::dynamic_pointer_cast<ServiceResponse>(msg_rsp);
                if (servise_rsp.get() == nullptr)
                {
                    ELOG("响应类型向下转换失败! ");
                    return false;
                }

                if (servise_rsp->rcode() != RCode::RCODE_OK)
                {
                    ELOG("服务注册失败, 原因: %S", errReason(servise_rsp->rcode()));
                    return false;
                }
                return true;
            }

        private:
            Requestor::ptr _requestor;
        };

        class MethodHost
        {
        public:
            using ptr = std::shared_ptr<MethodHost>;
            MethodHost(): _idx(0){}
            MethodHost(const std::vector<Address> hosts)
                : _hosts(hosts.begin(), hosts.end()), _idx(0)
            {
            }

            void appendHost(const Address &host)
            {
                // 中途收到服务上线请求;
                std::unique_lock<std::mutex> lock(_mutex);
                _hosts.push_back(host);
            }

            void removeHost(const Address &host)
            {
                std::unique_lock<std::mutex> lock(_mutex);
                for (auto it = _hosts.begin(); it != _hosts.end(); it++)
                {
                    if (*it == host)
                    {
                        _hosts.erase(it);
                        break;
                    }
                }
            }

            Address chooseHost()
            {
                std::unique_lock<std::mutex> lock(_mutex);
                size_t pos = _idx++ % _hosts.size();
                return _hosts[pos];
            }
            bool empty()
            {
                std::unique_lock<std::mutex> lock(_mutex);
                return _hosts.empty();
            }

        private:
            std::mutex _mutex;
            size_t _idx;
            std::vector<Address> _hosts;
        };

        class Discoverer
        {
        public:
            using offlineCallback = std::function<void(const Address&)>;
            using ptr = std::shared_ptr<Discoverer>;
            Discoverer(const Requestor::ptr &requestor, offlineCallback& cb) 
                    : _requestor(requestor) 
                    ,_offline_callback(cb)
                {}

            bool serviceDiscovery(const BaseConnection::ptr& conn, const std::string &method, Address &host)
            {
                {
                    std::unique_lock<std::mutex> lock(_mutex);
                    auto it = _method_hosts.find(method);
                    if (it != _method_hosts.end())
                    {
                        if (it->second->empty() == false)
                        {
                            host = it->second->chooseHost();
                            return true;
                        }
                    }
                }
                //当前服务提供者为空; 
                auto msg_req = MessageFactory::create<ServiceRequest>();
                UUID u;
                msg_req->setId(u.uuid());
                msg_req->setMType(MType::REQ_SERVICE);
                msg_req->setMethod(method);
                msg_req->setOptype(ServiceOpType::SERVICE_DISCOVERY);
                BaseMessage::ptr msg_rsp;
                bool ret = _requestor->send(conn, msg_req, msg_rsp);
                if(ret == false)
                {
                    ELOG("服务发现失败!");
                    return false;
                }
                auto service_rsp = std::dynamic_pointer_cast<ServiceResponse>(msg_rsp);
                if(!service_rsp)
                {
                    ELOG("响应类型转换失败!");
                    return false;
                }
                if(service_rsp->rcode() != RCode::RCODE_OK)
                {
                    ELOG("服务注册失败, 原因: %s", errReason(service_rsp->rcode()));
                    return false;
                }

                //当前没有对应服务提供的主机;
                std::unique_lock<std::mutex> lock(_mutex);
                auto method_host = std::make_shared<MethodHost>(service_rsp->Hosts());
                _method_hosts.insert(std::make_pair(method, method_host));
                if(method_host->empty())
                {
                    ELOG("服务发现失败, 没有可以提供服务的主机! ");
                    return false;
                }
                host = method_host->chooseHost();
                //_method_hosts.insert(std::make_pair(method, method_host));
                _method_hosts[method] = method_host;
                return true;
            }
            // 接口提供是进行上下线回调的函数;
            void onServiceRequest(const BaseConnection::ptr &conn, const ServiceRequest::ptr &msg)
            {
                //1. 判断是上线还是下线请求;
                auto optype = msg->Optype();
                std::string method = msg->method();
                std::unique_lock<std::mutex> lock(_mutex);
                //2. 上线请求, 找到methodHost新增一个主机地址;
                if(optype == ServiceOpType::SERVICE_ONLINE)
                {
                    auto it = _method_hosts.find(msg->method());
                    if(it == _method_hosts.end())
                    {
                        auto method_host = std::make_shared<MethodHost>();
                        method_host->appendHost(msg->host());
                        _method_hosts[method] = method_host;
                    }
                    else
                    {
                        it->second->appendHost(msg->host());
                    }
                }
                //3. 下线请求, 找到methodHost删除一个主机地址;
                else if(optype == ServiceOpType::SERVICE_OFFLINE)
                {
                     auto it = _method_hosts.find(msg->method());
                    if(it == _method_hosts.end())
                    {
                        return;
                    }
                    it->second->removeHost(msg->host());
                    _offline_callback(msg->host());
                }
            }

        private:
            offlineCallback _offline_callback;
            std::mutex _mutex;
            std::unordered_map<std::string, MethodHost::ptr> _method_hosts;
            Requestor::ptr _requestor;
        };
    }
}